var express = require('express');
var router = express.Router();
const os = require('os');
var moment = require('moment');
let { isArrayEmpty, urlf2z, FormatData, urlf2zList, isgender } = require('../util.js');
let { isAdminLogin, getUserCount, getUserList, DeleteUserById, GetUsersById, UpdateAdminById, GetAdminList, getAdminCount, GetAdminById, addMenutype,
  DeleteAdminById, addAdmin, getMenuCount, getMenuList, getMenuById, getMenutypeAll, delMenutype, addMenu, deleteMenuById, updataMenu, getRticleatypeAll, addRticleatype,
  delRticleatype, getRticleaList, addRticlea, getRticleaById, deleteRticleaById, updataRticlea, getRticleatCount, getUserListWord, getRticleaTable,
  getMenuTimeTable, getMotionCount, GetMotionList, addMotion, GetMotionById, DeletemotionById, UpdateMotionById
} = require('../mysql/index');
let upload = require('../util/multer/index')

router.post('/isAdminLogin', async (req, res, next) => {
  let { username, password, code } = req.body;
  // try {
  //   const sessionCaptcha = req.session.captcha.toLowerCase();
  //   if (sessionCaptcha != code) {
  //     return res.json({
  //       flog: 0,
  //       data: '验证码不正确'
  //     });
  //   }
  // } catch (error) {
  //   return res.json({
  //     flog: 0,
  //     data: '验证码不正确'
  //   });
  // }
  let data = await isAdminLogin({
    username,
    password
  });
  if (isArrayEmpty(data)) {
    jsonData = {
      code: 0,
      data: "账号或者密码错误"
    }
  } else {
    jsonData = {
      code: 1,
      data: {
        "access_token": username,
        "name": username,
        "userId": data[0].id
      }
    }
    req.session.AdminInfo = {
      username: username,
      userId: data[0].id,
      url: data[0].url
    }
  }
  return res.json(jsonData)
});

router.get('/adminInfo', async (req, res, next) => {
  if (!req.session.AdminInfo) {
    return res.json({
      code: 500,
      msg: "未登录"
    })
  }
  res.json(
    {
      "code": 200,
      "user": {
        "userId": req.session.AdminInfo.userId,
        "username": req.session.AdminInfo.username,
        "nickName": req.session.AdminInfo.username,
        "url": req.session.AdminInfo.url,
        "type": req.session.AdminInfo.type
      }
    }
  )
});

router.get('/getUserList', async (req, res, next) => {
  let { page, limit, userId, userName, userSex } = req.query;
  let count = await getUserCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  if (userSex) {
    userSex = userSex == '男' ? '0' : '1'
  }
  let data = await getUserList(num, limit, {
    userId, userName, userSex
  });
  data.data.forEach(item => item.userSex = isgender(item.userSex))
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.get('/GetUsersById', async (req, res, next) => {
  let id = req.query.editNo;
  let data = await GetUsersById(id);
  data.forEach(item => item.userSex = isgender(item.userSex))
  res.json({
    code: 1,
    data
  })
})

router.get('/DeleteUserById', async (req, res, next) => {
  let id = req.query.userId;
  let data = await DeleteUserById(id);
  res.json({
    code: 1,
    data
  })
})

router.post('/UpdateAdminPassById', async (req, res, next) => {
  let { oldPsw, newPsw } = req.body;
  let id = req.session.AdminInfo.userId;
  let username = req.session.AdminInfo.username;
  let admin = await isAdminLogin({
    username,
    password: oldPsw
  });
  if (admin.length) {
    await UpdateAdminById(id, {
      password: newPsw
    })
    return res.json({
      code: 200,
      msg: "修改密码成功"
    })
  } else {
    return res.json({
      code: 500,
      msg: "旧密码错误"
    })
  }
})

router.get('/GetAdminList', async (req, res, next) => {
  let { page, limit, id, name } = req.query;
  let count = await getAdminCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await GetAdminList(num, limit, {
    id, name
  });
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.get('/GetAdminById', async (req, res, next) => {
  let id = req.query.editNo;
  let data = await GetAdminById(id);
  res.json({
    code: 1,
    data
  })
})

router.post('/UpdateAdminById', upload.single('url'), async (req, res, next) => {
  let { id, name, password, sex, url } = req.body;
  url = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await UpdateAdminById(id, { name, password, sex, url });
  res.json({
    code: 1,
    data
  })
})

router.post('/DeleteAdminById', async (req, res, next) => {
  let { id } = req.body;
  await DeleteAdminById(id);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/addAdmin', upload.single('url'), async (req, res, next) => {
  let { name, password, sex, url } = req.body;
  url = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await addAdmin({ name, password, sex, url });
  res.json({
    code: 1,
    data
  })
})

router.get('/getMenuList', async (req, res, next) => {
  let { page, limit, menuId, menuName } = req.query;
  let count = await getMenuCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 0,
      data: []
    });
  }
  var num = (page - 1) * limit;
  let data = await getMenuList(num, limit, {
    menuId, menuName
  });
  res.json({
    code: 0,
    data: FormatData(data.data, {
      menuImgList: 'json',
      menuTag: 'json'
    }),
    count: data.count
  })
})

router.get('/getMenuById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await getMenuById(editNo);
  res.json({
    code: 1,
    data: FormatData(data, {
      menuImgList: 'json',
      menuTag: 'json',
      menuDate: 'date'
    })
  })
})

router.post('/deleteMenuById', async (req, res, next) => {
  let { menuId } = req.body
  await deleteMenuById(menuId)
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/getMenutypeAll', async (req, res, next) => {
  let data = await getMenutypeAll();
  res.json({
    code: 1,
    data
  })
})

router.post('/addMenutype', async (req, res, next) => {
  let { val } = req.body;
  let info = await addMenutype({
    menutypeTitle: val
  });
  if (!info.affectedRows) {
    return res.json({
      code: 0,
      data: "错误"
    })
  } else {
    res.json({
      code: 1,
      data: info
    })
  }
})

router.post('/delMenutype', async (req, res, next) => {
  let { menutypeId } = req.body;
  await delMenutype(menutypeId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/menuMaterialsuploadImg', upload.single('file'), async (req, res, next) => {
  let url = `${req.protocol}://${req.headers.host}/${req.file.path}`;
  res.json({
    code: 0,
    data: {
      "src": urlf2z(url)
    }
  })
})

router.post('/addMenu', upload.array('menuImg', 10), async (req, res, next) => {
  let countFile = req.files.length;
  let { menuName, menuType, menuPrice, menuTime, menuDate, menuComm, menuMaterials, menuTag, menuFlavor, menuHot } = req.body;
  if (countFile === 0) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  let menuImgList = urlf2zList(req);
  let menuImg = menuImgList[0];
  menuImgList = JSON.stringify(menuImgList);
  await addMenu({
    menuName, menuType, menuPrice, menuTime, menuDate, menuComm, menuMaterials, menuTag, menuFlavor, menuHot,
    menuImg: menuImg,
    menuImgList: menuImgList,
  })
  res.json({
    code: 1,
    data: "添加成功"
  })
})

router.post('/updataMenu', upload.array('menuImg', 10), async (req, res, next) => {
  let { menuName, menuType, menuPrice, menuTime, menuDate, menuComm, menuMaterials, menuTag, menuImgList, menuId, menuFlavor, menuHot } = req.body;
  let menuImgListUpdate = urlf2zList(req);
  menuImgList = JSON.parse(menuImgList);
  menuImgList = menuImgList.concat(menuImgListUpdate);
  let menuImg = menuImgList[0];
  menuImgList = JSON.stringify(menuImgList);
  if (!menuImgList.length) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  console.log(menuFlavor)
  await updataMenu(menuId, {
    menuName, menuType, menuPrice, menuHot, menuTime, menuDate, menuComm, menuMaterials, menuTag, menuImgList, menuImg, menuFlavor
  })
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/getRticleatypeAll', async (req, res, next) => {
  let data = await getRticleatypeAll();
  res.json({
    code: 1,
    data
  })
})

router.post('/addRticleatype', async (req, res, next) => {
  let { val } = req.body;
  let info = await addRticleatype({
    rticleatypeTitle: val
  });
  if (!info.affectedRows) {
    return res.json({
      code: 0,
      data: "错误"
    })
  } else {
    res.json({
      code: 1,
      data: info
    })
  }
})

router.post('/delRticleatype', async (req, res, next) => {
  let { rticleatypeId } = req.body;
  await delRticleatype(rticleatypeId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/getRticleaList', async (req, res, next) => {
  let { page, limit, rticleaType, rticleaTitle } = req.query;
  var num = (page - 1) * limit;
  let data = await getRticleaList(num, limit, {
    rticleaType, rticleaTitle
  });
  res.json({
    code: 0,
    data: FormatData(data.data, {
      rticleaImgList: 'json',
      rticleaTime: 'date'
    }),
    count: data.count
  })
})

router.post('/addRticlea', upload.array('rticleaImg', 10), async (req, res, next) => {
  let countFile = req.files.length;
  let { rticleaTitle, rticleaTime, rticleaType, rticleaComm, adminId } = req.body;
  adminId = req.session.AdminInfo.userId
  if (countFile === 0) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  console.log(adminId, req.session)
  let rticleaImgList = urlf2zList(req);
  rticleaImgList = JSON.stringify(rticleaImgList);
  await addRticlea({
    rticleaTitle, rticleaTime, rticleaType, rticleaComm, adminId,
    rticleaImgList: rticleaImgList,
  })
  res.json({
    code: 1,
    data: "添加成功"
  })
})

router.get('/getRticleaById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await getRticleaById(editNo);
  res.json({
    code: 1,
    data: FormatData(data, {
      rticleaImgList: 'json',
      rticleaTime: 'date'
    })
  })
})

router.post('/deleteRticleaById', async (req, res, next) => {
  let { rticleaId } = req.body
  await deleteRticleaById(rticleaId)
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/updataRticlea', upload.array('rticleaImg', 10), async (req, res, next) => {
  let { rticleaTitle, rticleaTime, rticleaType, rticleaComm, rticleaImgList, rticleaId } = req.body;
  let rticleaImgListUpdate = urlf2zList(req);
  rticleaImgList = JSON.parse(rticleaImgList);
  rticleaImgList = rticleaImgList.concat(rticleaImgListUpdate);
  rticleaImgList = JSON.stringify(rticleaImgList);
  if (!rticleaImgList.length) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  await updataRticlea(rticleaId, {
    rticleaTitle, rticleaTime, rticleaType, rticleaComm, rticleaImgList
  })
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/getIndexCount', async (req, res, next) => {
  let adminNum = await getAdminCount();
  let menuNum = await getMenuCount();
  let rticleatNum = await getRticleatCount();
  let userNum = await getUserCount();
  res.json({
    code: 1,
    adminNum, menuNum, rticleatNum, userNum
  })
})

router.get('/getuserNumTable', async (req, res, next) => {
  let DayList = [];
  for (var i = 1; i <= 7; i++) {
    DayList.push(moment().isoWeekday(i))
  }
  let { count, data } = await getUserListWord();
  let userNum = []
  DayList.forEach(dayItem => {
    let sunNum = 0;
    data.forEach(item => {
      if (dayItem.isSame(item.userTime, 'day')) {
        sunNum++;
      }
    })
    userNum.push(sunNum)
  })

  res.json({
    code: 1,
    userNum: userNum,
    count: count
  })

});

router.get('/getRticleaTable', async (req, res, next) => {
  let typeList = await getRticleatypeAll();
  let data = await getRticleaTable(typeList);
  data = JSON.parse(JSON.stringify(data))
  typeList = typeList.map(item => item.rticleatypeTitle)
  data = data.map(item => {
    return item[0]
  })
  res.json({
    code: 1,
    typeList,
    seriesData: data
  })
})

router.get('/getCpuTable', async (req, res, next) => {
  var freeMem = os.freemem() / 1024 / 1024 / 1024;
  var totalMem = os.totalmem() / 1024 / 1024 / 1024;
  res.json({
    code: 1,
    CpuNum: ((freeMem) / totalMem * 100.0).toFixed(2)
  })
})

router.get('/getMenuTimeTable', async (req, res, next) => {
  let typeList = [{ id: 1, menuTime: '早餐' }, { id: 2, menuTime: '午餐' }, { id: 3, menuTime: '晚餐' }]
  let data = await getMenuTimeTable(typeList);
  typeList = typeList.map(item => item.menuTime)
  data = data.map(item => {
    return item[0]
  })
  res.json({
    code: 1,
    data,
    typeList
  })
})

router.get('/getmotionList', async (req, res, next) => {
  let { page, limit, motionId, motionType } = req.query;
  let count = await getMotionCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 0,
      data: []
    });
  }
  var num = (page - 1) * limit;
  let data = await GetMotionList(num, limit, {
    motionId, motionType
  });
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.post('/addMotion', upload.single('motionImg'), async (req, res, next) => {
  let { motionType, motionHot, motionImg } = req.body;
  motionImg = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await addMotion({ motionType, motionHot, motionImg });
  res.json({
    code: 1,
    data
  })
})

router.get('/GetMotionById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await GetMotionById(editNo);
  res.json({
    code: 1,
    data: data
  })
})

router.get('/DeletemotionById', async (req, res, next) => {
  let { motionId } = req.query;
  await DeletemotionById(motionId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/UpdateMotionById', upload.single('motionImg'), async (req, res, next) => {
  let { motionType, motionHot, motionImg, motionId } = req.body;
  motionImg = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await UpdateMotionById(motionId, { motionType, motionHot, motionImg });
  res.json({
    code: 1,
    data
  })
})

module.exports = router;